package com.mf.interceptor;

import com.mf.basic.BasicKey;
import com.mf.entity.vo.UserVo;
import com.mf.exceptions.GraceException;
import com.mf.utils.AuthContextUtil;
import com.mf.utils.JWTUtil;
import com.mf.utils.RedisOperator;
import com.mf.utils.VerifyUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: lmf
 * @Create: 2024/7/10 11:28
 * Description:
 */
public class UserTokenInterceptor implements HandlerInterceptor {
    @Resource
    private RedisOperator redisOperator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户ID和令牌
        String token = request.getHeader("Token");


        UserVo userVo = checkToken(token);

        String redisToken = redisOperator.get(BasicKey.REDIS_USER_TOKEN + userVo.getNameAndId());
        if (VerifyUtils.isEmpty(redisToken) || !redisToken.equals(token)) {
            GraceException.display("用户信息异常,请重新登录");
            return false;
        }

        // 设置用户上下文信息
        AuthContextUtil.setUser(userVo);
        // 更新Redis中令牌的过期时间 (使用无感刷新token 这个好像不用刷新了)
//        redisOperator.expire(BasicKey.REDIS_USER_TOKEN + userId, BasicDuration.TOKEN_DURATION);

        return true; // 校验通过，继续处理请求
    }

    /**
     * 检验token是否存在
     */
    public static UserVo checkToken(String token) {
        if(VerifyUtils.isEmpty(token)){
            GraceException.display("用户信息异常,请重新登录");
        }

        UserVo userVo = JWTUtil.checkJwt(token);
        if (VerifyUtils.isEmpty(token) || userVo == null) {
            GraceException.display("用户信息异常,请重新登录");
        }
        return userVo;
    }
}
